# -*- coding:utf-8 -*-
# @Time :2025/3/10
import pymysql

class DbTools:
    # 数据库连接
    @classmethod
    def __connect(cls):
        conn = pymysql.connect(host='localhost', port=3306, user='root',
                               passwd='root', db='test', charset='utf8')
        return conn

    # 数据库查询
    @classmethod
    def query(cls, sql):
        conn = None
        cursor = None
        res = None
        try:
            conn = DbTools.__connect()
            cursor = conn.cursor()
            cursor.execute(sql)
            res = cursor.fetchall()
        except Exception as e:
            print("查询失败：", e)
        finally:
            cursor.close()
            conn.close()
            return res
    # 数据增删改
    @classmethod
    def update(cls, sql):
        conn = None
        cursor = None
        try:
            # 创建连接
            conn = DbTools.__connect()
            # 创建游标
            cursor = conn.cursor()
            # 执行 增删改 语句
            cursor.execute(sql)
            print("Affected rows:", conn.affected_rows())
            # 提交事务
            conn.commit()
        except Exception as err:
            print("执行 增删改 SQL 失败：", str(err))
            # 回滚事务
            conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            conn.close()